<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport"
        content="width=device-width,initial-scale=1,user-scalable=0,minimum-scale=1.0,maximum-scale=1.0" />
    <meta name="author" content="航天星云Satcloud">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no">
    <meta name="x5-fullscreen" content="true">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
    <title>测试页</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>

<body>
    <div>
        <img id="resImg" src="" />
    </div>
    <script>
        /**
         * Blob转文本
         * @param {Blob} blob 原始Blob数据
         * @param {string} type 要转换的类型，默认为Text
         * @returns {Promise<unknown>}
         */
        async function blob2Text(blob, type) {
            return new Promise(resolve => {
                const r = new FileReader();
                r.onloadend = function () {
                    resolve(r.result);
                }
                try {
                    r['readAs' + (type || "Text")](blob);
                } catch (e) {
                    console.log("Error：", e);
                }
            });
        }

        /**
         * 文本转Blob
         * @param {string} text 文本内容
         * @returns {Blob}
         */
        function text2Blob(text) {
            return new Blob([new Int16Array(0), text]);
        }


        let ws = new WebSocket("ws://127.0.0.1:8188/");
        ws.onopen = function (evt) {
            console.log("Connection open ...");
            ws.send("");
        };

        ws.onmessage = async function (evt) {
            const data = await blob2Text(evt.data)
            $("#resImg").attr("src", data);
            console.log("Received Message: " + data);
        };

        ws.onclose = function (evt) {
            console.log("Connection closed.");
        };

    </script>
</body>

</html>